<template>
  <el-dialog
    :title="dialogTitle"
    :visible="visible"
    width="90%"
    :modal="true"
    :append-to-body="true"
    top="5vh"
    :close-on-click-modal="false"
    class="template-preview-dialog"
    @close="handleClose"
  >
    <!-- 预览工具栏 -->
    <div class="preview-toolbar">
      <div class="toolbar-left">
        <span class="template-name">{{ template.name }}</span>
        <el-tag size="small">{{ getPageSizeText(template.pageSize) }}</el-tag>
        <el-tag size="small" :type="getTemplateTypeTag(template.type)">
          {{ getTemplateTypeText(template.type) }}
        </el-tag>
      </div>
      
      <div class="toolbar-right">
        <el-select
          v-model="currentTestDataId"
          placeholder="选择测试数据"
          size="mini"
          style="width: 200px; margin-right: 10px;"
          @change="loadTestData"
        >
          <el-option
            v-for="item in testDataList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        
        <el-button-group size="mini">
          <el-button 
            :type="zoomLevel === 0.8 ? 'primary' : ''" 
            @click="setZoom(0.8)"
          >
            80%
          </el-button>
          <el-button 
            :type="zoomLevel === 1 ? 'primary' : ''" 
            @click="setZoom(1)"
          >
            100%
          </el-button>
          <el-button 
            :type="zoomLevel === 1.2 ? 'primary' : ''" 
            @click="setZoom(1.2)"
          >
            120%
          </el-button>
        </el-button-group>
        
        <el-button 
          size="mini" 
          icon="el-icon-full-screen" 
          @click="toggleFullscreen"
          class="fullscreen-btn"
        >
          {{ isFullscreen ? '退出全屏' : '全屏' }}
        </el-button>
      </div>
    </div>

    <!-- 预览内容 -->
    <div class="preview-content-wrapper">
      <template-preview
        :template="template"
        :test-data="currentTestData"
        :mode="'preview'"
        ref="templatePreview"
        :style="{ transform: `scale(${zoomLevel})` }"
      />
    </div>

    <!-- 对话框底部 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关闭</el-button>
      
      <el-button 
        type="primary" 
        @click="handleGenerate('word')"
        icon="el-icon-document"
        :loading="generating"
      >
        生成Word文档
      </el-button>
      
      <el-button 
        type="success" 
        @click="handleGenerate('pdf')"
        icon="el-icon-document"
        :loading="generating"
      >
        生成PDF文档
      </el-button>
      
      <el-button 
        @click="handlePrint"
        icon="el-icon-printer"
      >
        打印
      </el-button>
    </div>

    <!-- 生成选项对话框 -->
    <el-dialog
      title="生成文档选项"
      :visible.sync="generateDialog.visible"
      width="500px"
      append-to-body
    >
      <el-form :model="generateDialog.form" label-width="100px">
        <el-form-item label="文档格式">
          <el-radio-group v-model="generateDialog.form.format">
            <el-radio label="word">Word文档</el-radio>
            <el-radio label="pdf">PDF文档</el-radio>
            <el-radio label="html">HTML网页</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="文件名称">
          <el-input
            v-model="generateDialog.form.filename"
            placeholder="请输入文件名称"
          />
        </el-form-item>
        
        <el-form-item label="包含数据">
          <el-checkbox-group v-model="generateDialog.form.includes">
            <el-checkbox label="basicInfo">基本信息</el-checkbox>
            <el-checkbox label="testData">测试数据</el-checkbox>
            <el-checkbox label="calculations">计算结果</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="generateDialog.visible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmGenerate" 
          :loading="generating"
        >
          生成文档
        </el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import TemplatePreview from './TemplatePreview.vue'

export default {
  name: 'TemplatePreviewDialog',
  components: {
    TemplatePreview
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    template: {
      type: Object,
      required: true,
      default: () => ({})
    },
    testData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 预览控制
      zoomLevel: 1,
      isFullscreen: false,
      
      // 测试数据
      testDataList: [],
      currentTestDataId: '',
      currentTestData: {},
      
      // 生成对话框
      generateDialog: {
        visible: false,
        form: {
          format: 'word',
          filename: '',
          includes: ['basicInfo', 'testData', 'calculations']
        }
      },
      generating: false
    }
  },
  computed: {
    dialogTitle() {
      return `模板预览 - ${this.template.name}`
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initializePreview()
      }
    },
    testData: {
      handler(newVal) {
        this.currentTestData = { ...newVal }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     * 初始化预览
     */
    initializePreview() {
      this.zoomLevel = 1
      this.isFullscreen = false
      this.loadTestDataList()
    },

    /**
     * 加载测试数据列表
     */
    loadTestDataList() {
      // 模拟测试数据列表
      this.testDataList = [
        { id: 'data1', name: '测试数据1 - 钢筋拉伸' },
        { id: 'data2', name: '测试数据2 - 混凝土抗压' },
        { id: 'data3', name: '测试数据3 - 综合检测' }
      ]
      
      if (this.testDataList.length > 0 && !this.currentTestDataId) {
        this.currentTestDataId = this.testDataList[0].id
        this.loadTestData()
      }
    },

    /**
     * 加载测试数据
     */
    loadTestData() {
      if (!this.currentTestDataId) return
      
      // 模拟加载测试数据
      this.currentTestData = {
        basicInfo: {
          sampleNo: 'TEST-2024-001',
          projectName: '示例工程项目',
          testDate: '2024-01-20',
          client: '示例客户',
          testStandard: 'GB/T 228.1-2010'
        },
        groups: [
          {
            groupId: 'GRP001',
            groupName: '样品信息',
            params: {
              sample_no: { value: 'SAMPLE-001', unit: '' },
              material_type: { value: 'HRB400', unit: '' },
              diameter: { value: 25, unit: 'mm' },
              test_temperature: { value: 25, unit: '°C' }
            }
          },
          {
            groupId: 'GRP002',
            groupName: '力学性能',
            params: {
              yield_strength: { value: 435.6, unit: 'MPa' },
              tensile_strength: { value: 567.8, unit: 'MPa' },
              elongation: { value: 22.5, unit: '%' }
            }
          }
        ]
      }
    },

    /**
     * 获取页面尺寸文本
     */
    getPageSizeText(pageSize) {
      const sizeMap = {
        A4: 'A4',
        A3: 'A3',
        custom: '自定义'
      }
      return sizeMap[pageSize] || pageSize
    },

    /**
     * 获取模板类型标签样式
     */
    getTemplateTypeTag(type) {
      const tagMap = {
        record: 'primary',
        report: 'success'
      }
      return tagMap[type] || 'info'
    },

    /**
     * 获取模板类型文本
     */
    getTemplateTypeText(type) {
      const textMap = {
        record: '原始记录',
        report: '检测报告'
      }
      return textMap[type] || '未知类型'
    },

    /**
     * 设置缩放级别
     */
    setZoom(level) {
      this.zoomLevel = level
    },

    /**
     * 切换全屏模式
     */
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
      
      if (this.isFullscreen) {
        document.documentElement.requestFullscreen?.()
      } else {
        document.exitFullscreen?.()
      }
    },

    /**
     * 处理生成文档
     */
    handleGenerate(format) {
      this.generateDialog.form.format = format
      this.generateDialog.form.filename = `${this.template.name}_${new Date().getTime()}`
      this.generateDialog.visible = true
    },

    /**
     * 确认生成文档
     */
    async confirmGenerate() {
      this.generating = true
      
      try {
        const generateData = {
          template: this.template,
          testData: this.currentTestData,
          options: this.generateDialog.form
        }
        console.log('generateData',generateData)
        
        // 调用API生成文档
        // const result = await this.$api.report.generate(generateData)
        
        // 模拟生成成功
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        this.$message.success('文档生成成功')
        this.generateDialog.visible = false
        
        // 模拟下载文件
        this.downloadMockFile()
        
        // 触发生成事件
        this.$emit('generate', this.generateDialog.form.format)
      } catch (error) {
        console.error('生成文档失败:', error)
        this.$message.error('生成文档失败')
      } finally {
        this.generating = false
      }
    },

    /**
     * 模拟下载文件
     */
    downloadMockFile() {
      const format = this.generateDialog.form.format
      const extension = format === 'word' ? 'docx' : format
      const blob = new Blob(['模拟文件内容'], { type: 'application/octet-stream' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${this.generateDialog.form.filename}.${extension}`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    },

    /**
     * 处理打印
     */
    handlePrint() {
      if (this.$refs.templatePreview) {
        this.$refs.templatePreview.print()
      }
    },

    /**
     * 处理关闭
     */
    handleClose() {
      this.$emit('close')
    }
  }
}
</script>

<style scoped>
.template-preview-dialog {
  margin: 0;
}

.template-preview-dialog :deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  height: 90vh;
}

.template-preview-dialog :deep(.el-dialog__body) {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e6e8eb;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.template-name {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.fullscreen-btn {
  margin-left: 10px;
}

.preview-content-wrapper {
  flex: 1;
  padding: 20px;
  background: #f0f2f5;
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  transition: transform 0.3s ease;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  flex-shrink: 0;
}

/* 全屏样式 */
:fullscreen .template-preview-dialog :deep(.el-dialog) {
  width: 100% !important;
  height: 100% !important;
  max-width: none !important;
  max-height: none !important;
  margin: 0 !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .preview-toolbar {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .toolbar-right {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .template-preview-dialog {
    width: 95% !important;
  }
  
  .preview-toolbar {
    padding: 10px 15px;
  }
  
  .toolbar-right {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .toolbar-right .el-select {
    width: 100% !important;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}
</style>